﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Threading;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using System.Diagnostics;

namespace CertSearch
{
    #region Enum
    public enum SearchType
    {
        Thumbprint,
        Name
    }
    #endregion

    #region Delegates
    delegate void OneArgDelegate(String arg);
    delegate void TwoArgDelegate(String arg1, String arg2);
    #endregion

    /// <summary>
    /// Interaction logic for CertSearchWindow.xaml
    /// </summary>
    public partial class CertSearchWindow : Window
    {
        #region Private Fields
        private string sDir, searchText, searchType;
        private bool continueSearching = false;
        #endregion

        # region Constructor
        public CertSearchWindow()
        {
            InitializeComponent();
            Loaded += CertSearchWindow_Loaded;
        }
        # endregion

        #region Private Methods

        private void CertSearchWindow_Loaded(object sender, RoutedEventArgs e)
        {
            cboDirectory.Items.Clear();

            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                if (drive.DriveType != DriveType.CDRom)
                    cboDirectory.Items.Add(drive.Name);
            }

            cboDirectory.Text = cboDirectory.Items[0].ToString();

            cboSearchType.Items.Clear();
            cboSearchType.Items.Add(SearchType.Thumbprint.ToString());
            cboSearchType.Items.Add(SearchType.Name.ToString());

            cboSearchType.Text = SearchType.Thumbprint.ToString();
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            sDir = cboDirectory.SelectedItem.ToString();
            searchText = txtToBeSearched.Text;
            searchType = cboSearchType.Text;

            string messageBoxText = "Please enter the " + cboSearchType.Text + " of the Certificate ! Clicking Cancel will close the application.";
            string caption = "Search Cert";
            MessageBoxButton button = MessageBoxButton.OKCancel;
            MessageBoxImage icon = MessageBoxImage.Warning;

            if ((searchText == null || searchText == string.Empty))
            {
                MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);

                switch (result)
                {
                    case MessageBoxResult.OK:
                        txtToBeSearched.Focus();
                        continueSearching = true;
                        break;

                    case MessageBoxResult.Cancel:
                        this.Close();
                        break;
                }
            }
            if (continueSearching)
            {
                continueSearching = false;
                btnSearch.Content = "Restart Search";
            }
            else
            {
                continueSearching = true;
                btnSearch.Content = "Stop Search";

                TwoArgDelegate searcher = new TwoArgDelegate(this.DirSearch);
                searcher.BeginInvoke(sDir, searchText, new AsyncCallback(UpdateSearchResult), null);
            }
        }

        private void btnClearList_Click(object sender, RoutedEventArgs e)
        {
            lstFilesFound.Items.Clear();
        }

        private void cboSearchType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cboSearchType.SelectedIndex != -1)
            {
                txtToBeSearched.Text = String.Empty;
            }
        }

        private void lstFilesFound_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lstFilesFound.SelectedIndex != -1)
            {
                OpenFolder(lstFilesFound.SelectedItem.ToString());
            }
        }

        /// <summary>
        /// Search Directory
        /// </summary>
        /// <param name="sDir"></param>
        /// <param name="searchText"></param>
        private void DirSearch(string sDir, string searchText)
        {
            bool authorized;
            try
            {
                foreach (string d in Directory.GetDirectories(sDir))
                {
                    authorized = true;
                    btnSearch.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new OneArgDelegate(UpdateSearchStatus), "Searching:- " + d);
                    try
                    {
                        foreach (string f in Directory.GetFiles(d))
                        {
                            FileInfo fi = new FileInfo(f);
                            if (fi.Extension.Contains("pfx") || fi.Extension.Contains("cer"))
                            {
                                try
                                {
                                    // Get the certificate bytes
                                    byte[] certBytes = File.ReadAllBytes(fi.FullName);
                                    X509Certificate2 cert = new X509Certificate2(certBytes);
                                    if (searchType == SearchType.Thumbprint.ToString())
                                    {
                                        if (cert.Thumbprint == searchText.Trim())
                                        {
                                            if (!lstFilesFound.Items.Contains(f))
                                            {
                                                lstFilesFound.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
                                                {
                                                    lstFilesFound.Items.Add(f);
                                                }
                                                ));
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (cert.SubjectName.Name.Contains(searchText.Trim()))
                                        {
                                            lstFilesFound.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
                                            {
                                                lstFilesFound.Items.Add(f);
                                            }
                                            ));
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                    catch (UnauthorizedAccessException uae)
                    {
                        authorized = false;
                    }
                    if (authorized && continueSearching)
                    {
                        DirSearch(d, searchText);
                    }
                }
            }
            catch (Exception e)
            {
                //Something weird has happened;
            }
        }

        /// <summary>
        /// Update search status
        /// </summary>
        /// <param name="message">message </param>
        private void UpdateSearchStatus(string message)
        {
            lblStatus.Content = message;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="result"></param>
        private void UpdateSearchResult(IAsyncResult result)
        {
            if (!continueSearching)
            {
                btnSearch.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new OneArgDelegate(UpdateSearchStatus), "Search Aborted.  " + "Files Found = " + lstFilesFound.Items.Count);
            }
            else
            {
                btnSearch.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new OneArgDelegate(UpdateSearchStatus), "Search Completed.  " + "Files Found = " + lstFilesFound.Items.Count);
                btnSearch.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
                {
                    btnSearch.Content = "Begin Search";
                }
                )); continueSearching = false;
                
            }
        }

        /// <summary>
        /// OpenFolder
        /// </summary>
        /// <param name="path"></param>
        private static void OpenFolder(string filename)
        {
            FileInfo fi = new FileInfo(filename);
            string folder = fi.DirectoryName;
            Process p = new Process();
            p.StartInfo.FileName = folder;
            p.Start();
        }

        #endregion
    }
}